home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14108 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: news.umbc.edu!not-for-mail
  2. From: schlein@umbc.edu (Jonas J. Schlein)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Recursion
  5. Date: 11 Apr 1996 18:35:39 -0400
  6. Organization: University of Maryland Baltimore County
  7. Message-ID: <4kk1fr$9jt@umbc9.umbc.edu>
  8. References: <31624BC2.70D2@sooner.net>
  9. NNTP-Posting-Host: umbc9.umbc.edu
  10. NNTP-Posting-User: schlein
  11.  
  12. In article <31624BC2.70D2@sooner.net>, Eddie Bush  <edwbush@sooner.net> wrote:
  13. |> I am trying to construct a C function that will recursively convert
  14. |> a string such as "1234" into it's integer equivelant (1234).
  15.  
  16. Why recursively and what about the atoi() function that already exists?
  17.  
  18. |> Here is what I know:
  19. |> 1)if you subtract the character "0" from any of the other digits "1".."9"
  20. |>   you will get the integer value of that characer.
  21. |>     Example:  "1" - "0" is equal to 1
  22. |>           "2" - "0" is equal to 2
  23. |>           .
  24. |>           .
  25. |>           .
  26. |>           "9" - "0" is equal to 9
  27.  
  28. If you replace those strings (enclosed in "") with characters (enclosed in '')
  29. then I will agree with you.
  30.  
  31. |> 2)the function should be called with a character pointer:
  32. |>     Such as:   convert("1234");
  33. |>   making the prototype look something like:
  34. |>     int convert(char *p);
  35.  
  36. I'd make it 'int convert (const char *p);', but that's just my personal
  37. preference.
  38.  
  39. |> Does anyone have an idea?  This is sorta stumping me.  I am aware of 
  40. |> atoi, but I am wanting to write a recursive function that does that -- 
  41. |> for the fun of it.  It's sort of a little puzzle to help me learn 
  42. |> recursion.  Any ideas?
  43.  
  44. I don't see how it would be fun, but anything can be done recursively if
  45. you want it bad enough. Here's something to get you started that is both
  46. incomplete and possibly wrong altogether (aka untested):
  47.  
  48. int convert (const char *p)
  49. {
  50.   if (strlen (p) == 1)
  51.      return (p[0] - '0');
  52.   return ((int)(pow ((p[0] - '0'), (strlen (p) - 1)) + convert (&p[1])));
  53. }
  54.  
  55. Just make sure you #include <math.h> and <string.h>. This is far from the
  56. most efficient solution, but at least it's recursive.
  57. -- 
  58. "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
  59.  
  60. Jonas J. Schlein  (schlein@gl.umbc.edu)
  61.